<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>susu聊天室</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f8ff; /* 天蓝色背景 */
            color: #333;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }

        .container {
            display: flex;
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #ffffff;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .content {
            flex: 1;
            margin-right: 20px;
            border: 1px solid #ddd;
            border-radius: 10px;
            padding: 20px;
            overflow-y: auto;
            max-height: 500px;
            background-color: #f8f8ff; /* 浅蓝色背景 */
        }

        .msg {
            display: flex;
            align-items: flex-start;
            margin-bottom: 10px;
        }

        .msg .time {
            color: #888;
            font-size: 0.8em;
            margin-right: 10px;
        }

        .msg .name {
            color: #4682b4; /* 深蓝色 */
            font-weight: bold;
            margin-right: 5px;
        }

        .msg .message {
            flex: 1;
            background-color: #e0ffff; /* 浅蓝色 */
            padding: 5px 10px;
            border-radius: 5px;
        }

        .sidebar {
            width: 300px;
            background-color: #f0f8ff; /* 天蓝色 */
            border-radius: 10px;
            padding: 20px;
        }

        .line {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }

        .line input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            margin-right: 10px;
        }

        .line button {
            padding: 10px 20px;
            background-color: #4682b4; /* 深蓝色 */
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .line button:hover {
            background-color: #5a9bd4;
        }

        .line-top {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }

        .line-title {
            font-weight: bold;
            margin-bottom: 5px;
        }

        .line-content {
            background-color: #e0ffff; /* 浅蓝色 */
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 10px;
        }

        .info {
            position: fixed;
            top: 20%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: lightgray;
            padding: 1rem;
            border-radius: 1rem;
            opacity: 0.9;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="content">
        <!-- 消息列表 -->
    </div>
    <div class="sidebar">
        <div class="line">
            <div>用户名称</div>
            <input name="username" placeholder="请输入用户名" value="游客">
        </div>
        <div class="line">
            <div>消息内容</div>
            <input name="message" placeholder="请输入内容" value="">
        </div>
        <div class="line">
            <button>发送</button>
            <button>清屏</button>
        </div>
        <div class="line-top">
            <div class="line-title">消息排行</div>
            <div id="msgHis"></div>
        </div>
        <div class="line-top">
            <div class="line-title">在线列表</div>
            <div id="online"></div>
        </div>
    </div>
</div>

<script type="module">
    let elContent = document.getElementsByClassName('content').item(0)
    let elUsername = document.getElementsByName('username').item(0)
    let elMessage = document.getElementsByName('message').item(0)
    //let msgHisMessage = document.getElementsByName('message').item(0)
    let btnSend = document.getElementsByTagName('button').item(0)
    let btnClear = document.getElementsByTagName('button').item(1)

    let elMsgHis = document.getElementById('msgHis')
    let elOnline = document.getElementById('online')

    let queryGet = async (url) => await (await fetch(url)).json()
    setInterval(async () => {
        let res = await queryGet('http://localhost:9090/messageRank/top10')
        if (res.code == 0) {
            let dataArr = res.data
            Array.from(elMsgHis.children).forEach(e => e.remove())
            dataArr.forEach(e => {
                let { name, score, id } = e
                let msg = `${name} ${score}`
                let el = document.createElement('div')
                el.innerHTML = msg;
                elMsgHis.appendChild(el)
            })

        }
    }, 5000);
    setInterval(async () => {
        let res = await queryGet('http://localhost:9090/onlineUsers/list')
        if (res.code == 0) {
            let dataArr = res.data
            Array.from(elOnline.children).forEach(e => e.remove())
            dataArr.forEach(e => {
                let sp = e.split('::')
                let userId = sp[0]
                let name = sp[1]
                let msg = `${name}`
                let el = document.createElement('div')
                el.innerHTML = msg;
                elOnline.appendChild(el)
            })

        }
    }, 5000);


    let queryObj = decodeURIComponent(location.search).split('?').pop().split('&').reduce((res, ele, ind) => {
        let sp = ele.split('=')
        res[sp[0]] = sp[1]
        return res
    }, {})
    if (!queryObj.userId) {
        alert('用户id未填写')
        location.href = '/'
        throw new Error('用户id未填写')
    }
    let serverUrl = 'http://localhost:9090'
    let wsUrl = 'ws://localhost:9090/chat/' + queryObj.userId
    let ws
    let wsErr = false
    function doConnect() {
        ws = new WebSocket(wsUrl)
        ws.onclose = () => {
            if (!wsErr) {
                showMsg({ username: '系统', message: '聊天室已断开' })
                wsErr = true
            }
            setTimeout(doConnect, 2000)
        }
        ws.onopen = async () => {
            wsErr = false
            showMsg({ username: '系统', message: '聊天室已连接' })

            let detailUrl = `http://localhost:9090/user/detail?id=${queryObj.userId}`
            let res = await queryGet(detailUrl)
            if (res.code == 0) {
                elUsername.value = res.data.name
            }
        }
        ws.onmessage = (event) => {
            let data = event.data
            try {
                let msg = JSON.parse(data)
                showMsg(msg)
            } catch (err) {
                showMsg({ username: '系统', message: String(data) })
            }
        }
    }
    doConnect()

    function getMsg() {
        let username = elUsername.value
        let message = elMessage.value
        return { username, message }
    }
    function showMsg(msg = { username: '', time: '', message: '' }) {
        let { username = '', time = Date.now(), message = '' } = msg
        let timeStr
        if (typeof (time) == 'number') {
            timeStr = new Date(time).toLocaleTimeString()
        } else {
            timeStr = new Date(String(time).substring(0, 19)).toLocaleTimeString()
        }
        let msgLine = document.createElement('div')
        msgLine.className = 'msg'
        msgLine.innerHTML = `<div class="name">${username}</div>
            <div class="time">${timeStr}</div>
            <div>${message}</div>`
        elContent.insertBefore(msgLine, elContent.firstElementChild)
    }
    function info(msg = '') {
        let elInfo = document.createElement('div')
        elInfo.className = 'info'
        elInfo.innerHTML = `${msg}`
        document.body.appendChild(elInfo)
        setTimeout(() => elInfo.remove(), 2000)
    }
    function sendMsg() {
        let { username, message } = getMsg()
        if (!username) {
            info('用户名称未填写')
            return
        }
        if (!message) {
            info('消息内容未填写')
            return
        }
        localStorage['username'] = username
        elMessage.value = ''
        ws.send(JSON.stringify({ username, message }))
    }
    function clear() {
        elContent.innerHTML = ''
    }
    async function load() {
        let res = await fetch(serverUrl + "/History/listHistory")
        let json = await res.json()
        window.json = json
        console.log('json', json)
        if (json.data.records != null) {
            // for (let i = 0; i < json.data.records.length; i++) {
            //     let his = json.data.records[i]
            //     showMsg(his)
            // }
            // @since 2025-3-20 15:24:38 修复历史消息内容顺序不是最新的在前面的问题
            json.data.records.reverse().forEach(his => showMsg(his))
        }
    }
    document.body.onload = async () => {
        btnSend.onclick = sendMsg
        btnClear.onclick = clear
        elUsername.value = localStorage['username'] || elUsername.value
        clear()
        load()
    }




</script>

</body>

</html>